#!/usr/bin/python
# -*- coding: UTF-8 -*-

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.externals import joblib

# 1.加载数据
path = '../datas/household_power_consumption_201.txt'
data = pd.read_csv(filepath_or_buffer=path, sep=";")

# 2. 数据清洗
data.replace('?',np.nan,inplace=True)
data = data.dropna(axis=0,how='any')
# print(data.info())

# 3. 构建特征属性和目标属性
X = data.iloc[:, 2:4]
Y = data.iloc[:, 5]

# 4. 数据分割，分割测试集和训练机
x_train,x_test,y_train,y_test = train_test_split(X, Y, train_size=0.8, random_state=28)


# 5. 特征工程
# 操作可选
# 主要就是：哑编码、连续数据离散化、数据的转换、标准化、归一化、降维.....


# 6. 算法/模型对象构建
algo = LinearRegression()

# 7. 训练
algo.fit(x_train,y_train)

# 8. 模型效果评估
print("模型效果：{}".format(algo.score(x_train,y_train)))

# 9. 模型保存
# a. 保存模型
joblib.dump(algo,'./linear')

# b. 保存预测结果
y_hat = algo.predict(x_test)
plt.figure(facecolor='w')
t=np.arange(len(x_test))
plt.plot(t,y_test,'r-',label="scoure")
plt.plot(t,y_hat,'b-',label="result")
plt.legend('lower right')
plt.show()

if __name__ == '__main__':
    pass